//
//  MHViewController.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHViewController.h"
#import "MHNavigationController.h"
#import "MHHttpCache.h"
@interface MHViewController ()

// viewModel
@property (nonatomic, readwrite, strong) MHViewModel *viewModel;
@property(nonatomic, assign) CGFloat oldHeight;
@end

@implementation MHViewController

- (void)dealloc
{
    /// 销毁时保存数据
    //    [SBPhotoManager configureSelectOriginalPhoto:_isSelectOriginalPhoto];
    MHDealloc;
}

// when `BaseViewController ` created and call `viewDidLoad` method , execute `bindViewModel` method
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    MHViewController *viewController = [super allocWithZone:zone];
    @weakify(viewController)
    [[viewController
      rac_signalForSelector:@selector(viewDidLoad)]
     subscribeNext:^(id x) {
         @strongify(viewController)
         [viewController bindViewModel];
     }];
    return viewController;
}



- (instancetype)initWithViewModel:(MHViewModel *)viewModel {
    self = [super init];
    if (self) {
        self.viewModel = viewModel;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /// 隐藏导航栏细线
    self.viewModel.prefersNavigationBarBottomLineHidden?[(MHNavigationController *)self.navigationController hideNavigationBottomLine]:[(MHNavigationController *)self.navigationController showNavigationBottomLine];
    /// 配置键盘
    
//    if (self.translusentNavStatus) {
//        [self.navigationController.navigationBar setTranslucent:YES];
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar_bg_tranlusent"] forBarMetrics:UIBarMetricsDefault];
//    }
    if (self.viewModel.translucentNavigationBar) {
//        [self setStatusBarBackgroundColor:[UIColor clearColor]];
        UIColor *alphaColor =  [UIColor clearColor]; //[[UIColor blackColor] colorWithAlphaComponent:0.3];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new]  forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        self.navigationController.navigationBar.translucent = YES;
//        [self.
//        [self.activityButton.layer removeAllAnimations];
//        [self.activityButton shake:CGFLOAT_MAX withDelta:20 speed:0.1 shakeDirection:ShakeDirectionRotation completion:nil];
    }
    
    if (self.viewModel.changeNavTitle) {
        NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
        textAttrs[NSFontAttributeName] =  MHMediumFont(FontSizeFromPixel(24));
        textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
        [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
//        [UIApplication sharedApplication] set
        self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
   
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        
    }

    IQKeyboardManager.sharedManager.enable = self.viewModel.keyboardEnable;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = self.viewModel.shouldResignOnTouchOutside;
    IQKeyboardManager.sharedManager.keyboardDistanceFromTextField = self.viewModel.keyboardDistanceFromTextField;
    
    
//    for (UIView *view in self.navigationController.navigationBar.subviews[2].subviews) {
//        if ([view isKindOfClass:UIStackView.class]) {
//            view.layoutMargins = UIEdgeInsetsMake(0, -15, 0, 0);
//        }
//    }
    
    
    /// 这里做友盟统计
    //    [MobClick beginLogPageView:SBPageName(self)];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.viewModel.willDisappearSignal sendNext:nil];
    
    // Being popped, take a snapshot
    if ([self isMovingFromParentViewController]) {
        self.snapshot = [self.navigationController.view snapshotViewAfterScreenUpdates:NO];
    }
    
  


    
    if (self.viewModel.translucentNavigationBar) {
        if (!self.viewModel.changeNavTitle) {
             [self setStatusBarBackgroundColor:[UIColor clearColor]];
        }
       
        [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        self.navigationController.navigationBar.translucent = NO;
        
    }
    
    if (self.viewModel.changeNavTitle) {
        NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
        textAttrs[NSFontAttributeName] =  MHMediumFont(FontSizeFromPixel(24));
        textAttrs[NSForegroundColorAttributeName] = MHTextColor333;
        [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
//        self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
//        [self setNeedsStatusBarAppearanceUpdate];
    }
//    if (self.translusentNavStatus) {
//        [self.navigationController.navigationBar setTranslucent:NO];
//        [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
////        UINavigationBar *appearance = [UINavigationBar appearance];
////        [appearance setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
////        self.navigationController.navigationBar.clipsToBounds = YES;//去掉白线
//    }
    /// 这里做友盟统计
    //    [MobClick endLogPageView:SBPageName(self)];
}

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    NSLog(@"statusBar.backgroundColor--->%@",statusBar.backgroundColor);
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    /// ignore adjust auto scroll 64
    /// CoderMikeHe: 适配 iOS 11.0 ,iOS11以后，控制器的automaticallyAdjustsScrollViewInsets已经废弃，所以默认就会是YES
    /// iOS 11新增：adjustContentInset 和 contentInsetAdjustmentBehavior 来处理滚动区域
    ///
    if (@available(iOS 11.0, *)) {
        self.automaticallyAdjustsScrollViewInsets = YES;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    /// backgroundColor
    self.view.backgroundColor = MH_MAIN_BACKGROUNDCOLOR;
    
//    self.edgesForExtendedLayout = UIRectEdgeAll;
    
    /// 导航栏隐藏 只能在ViewDidLoad里面加载，无法动态
    self.fd_prefersNavigationBarHidden = self.viewModel.prefersNavigationBarHidden;
    
    /// pop手势
    self.fd_interactivePopDisabled = self.viewModel.interactivePopDisabled;
    
    [RACObserve([UIApplication sharedApplication], statusBarFrame) subscribeNext:^(id x) {
        if ([UIApplication sharedApplication].statusBarFrame.size.height > 20) {

            ((AXAppDelegate*)[[UIApplication sharedApplication] delegate]).window.frame = CGRectMake(0, 0, MH_SCREEN_WIDTH, MH_SCREEN_HEIGHT - 20 );

        }else{

           ((AXAppDelegate*)[[UIApplication sharedApplication] delegate]).window.frame = CGRectMake(0, 0, MH_SCREEN_WIDTH, MH_SCREEN_HEIGHT);
        }
    }];
    
    

    if (!self.viewModel.hiddenNavShadow) {
        self.navigationController.navigationBar.layer.shadowColor = [UIColor blackColor].CGColor;
        self.navigationController.navigationBar.layer.shadowOffset = CGSizeMake(0, 1);
        self.navigationController.navigationBar.layer.shadowOpacity = 0.1;
    }
    
    
    
    
//    [self transluentTwoStyle];
    

    
    
}

//- (void)transluentTwoStyle{
//    NSArray *ary  = [self.navigationController.navigationBar subviews];
//    UIColor *alphaColor = [UIColor clearColor];
//    for (int i = 0; i < ary.count; i++) {
//        UIView *view = ary[i];
//        view.backgroundColor = alphaColor;
//        for (int j = 0; j < view.subviews.count; j++) {
//            UIView *subView = view.subviews[j];
//            subView.backgroundColor = alphaColor;
//            for (int k = 0; k < subView.subviews.count; k++) {
//                UIView *subsubView = subView.subviews[k];
//                subsubView.backgroundColor = alphaColor;
//            }
//        }
//        if([view isKindOfClass:NSClassFromString(@"_UIBarBackground")]) {
//            view.backgroundColor = alphaColor;
//        }
//    }
//}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([otherGestureRecognizer.delegate isKindOfClass:NSClassFromString(@"_FDFullscreenPopGestureRecognizerDelegate")]) {
        [MHMomentHelper hideAllPopViewWithAnimated:YES];
        return YES;
    }

    return NO;
}



-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    YYImageCache *cache = [YYWebImageManager sharedManager].cache;
    [cache.memoryCache removeAllObjects];
    [cache.diskCache removeAllObjects];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
//    [[MHHttpCache sharedInstance].cache removeAllObjects];

}

// bind the viewModel
- (void)bindViewModel{
    /// set navgation title
    /// CoderMikeHe Fixed: 这里只是单纯设置导航栏的title。 不然以免self.title同时设置了navigatiItem.title, 同时又设置了tabBarItem.title
    
    NSLog(@"--- %@" , self.viewModel.title);
    @weakify(self);
    
    RAC(self.navigationItem , title) = RACObserve(self, viewModel.title);
    /// 绑定错误信息
    [self.viewModel.errors subscribeNext:^(NSError *error) {
        @strongify(self);
        /// 这里可以统一处理某个错误，例如用户授权失效的的操作
//        if (error.code == -1) {
//            [[self.viewModel.fetchTokenCommand execute:nil] subscribeError:^(NSError *error) {
//                if (error.code == 3)
//                {
//                    [self.viewModel.redirectLoginCommand execute:nil];
//                }
//            }];
//            NSLog(@"...Token失效...");
//        }else
        NSLog(@"...错误...");
    }];
    
    /// 动态改变
    [[[RACObserve(self.viewModel, interactivePopDisabled) distinctUntilChanged] deliverOnMainThread] subscribeNext:^(NSNumber * x) {
        @strongify(self);
        self.fd_interactivePopDisabled = x.boolValue;
    }];
}

-(void)openCameraIsPublish:(BOOL) isPublish selectedAssets:(NSArray *)selecatedAssets completionBlock:(VoidBlock_id_id)completionBlock  {
    [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:isPublish?9:1 allowCrop:NO selectedAssets:selecatedAssets completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        NSMutableArray *photesArray =  [MHPhotoManager selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
        completionBlock(photesArray,assets);
    } cancel:^{
        
    }];
}

-(void) rightButtonClic{};
#pragma mark - Orientation
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {return UIInterfaceOrientationMaskPortrait;}
- (BOOL)shouldAutorotate {return YES;}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {return UIInterfaceOrientationPortrait;}

#pragma mark - Status bar
- (BOOL)prefersStatusBarHidden { return NO; }
- (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleDefault; }
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation { return UIStatusBarAnimationFade; }

@end
